import { createRouter, createWebHistory,createWebHashHistory } from 'vue-router'
import {useUserStore} from "@/stores/index.js";
// createRouter 创建路由实例
// 配置 history 模式
// 1. history模式: createWebHistory  地址栏不带 #
// 2. history模式: createWebHashHistory  地址栏带 #
const router = createRouter({
  // vite 中的环境变量, import.meta.env.BASE_URL 就是vite.config.js中的base配置项
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: ()=>import('@/views/login/LoginPage.vue')
    },
    {
      path: '/',
      component: ()=> import('@/views/layout/LayoutContainer.vue'),
      redirect: '/article/manage',
      children: [
        {
          path: '/article/manage',
          component: ()=>import('@/views/article/ArticleManage.vue'),
        },
        {
          path: '/article/channel',
          component: ()=>import('@/views/article/ArticleChannel.vue'),
        },
        {
          path: '/user/profile',
          component: ()=>import('@/views/user/UserProfile.vue'),
        },
        {
          path: '/user/avatar',
          component: ()=>import('@/views/user/UserAvatar.vue'),
        },
        {
          path: '/user/password',
          component: ()=>import('@/views/user/UserPassword.vue'),
        }
      ]
    }
  ]
})

// 登录访问拦截
router.beforeEach((to) => {
  // 判断有没有token, 且访问的是非登录页, 拦截到登录, 其他情况正常放行
  const useStore = useUserStore()
  if (!useStore.token && to.path !== '/login') return '/login'
  // if (!useStore.token && to.name !== 'login') return { name: 'login' }  这个需要再routes中配置name属性
  // return true
})
export default router
